/*
 * @Description: 本文件实现egg事务功能处理
 * @Author: 听风
 * @Date: 2020-12-24 10:29:43
 */

const Handlebars = require('handlebars');
const Ora = require('ora');
const Inquirer = require('inquirer');
const {
  downloadGitTemp,
  readFileFromRoot,
  writeFileOnRoot,
  renameFileOnRoot,
  existsSync,
} = require('../uitls/fs');

/**
 * @description: 添加resftul接口
 * @param {*} restfulName
 * @param {*} path
 * @return {*}
 */
const restfulRouter = async (filename, log = true) => {
  const savePath = 'app/router';
  const fileLocation = `${savePath}/restful.js`;
  // 路由文件单独处理
  if (!existsSync(fileLocation, false)) {
    // 文件不存在则载入
    // 载入重命名
    const spinner = log ? Ora('正在载入...').start() : null;
    await downloadGitTemp('egg-router', savePath);
    await renameFileOnRoot(`${savePath}/_egg_router.js`, fileLocation);
    const content = await readFileFromRoot(fileLocation);

    // 渲染模板
    const meta = {
      name: filename,
    };
    const file = Handlebars.compile(content)(meta);
    await writeFileOnRoot(fileLocation, file);
    log && spinner.succeed('载入完成');
    return;
  }
  const spinner = log ? Ora('正在处理...').start() : null;
  const lines = (await readFileFromRoot(fileLocation)).split(/\r\n|\n|\r/gm); //readFileSync的第一个参数是文件名
  let restfulesStr = '',
    startIndex = 0,
    endIndex = 0;
  for (let index in lines) {
    const line = lines[index];
    if (!restfulesStr && line.startsWith('const restfuls = ')) {
      restfulesStr = line;
      startIndex = index;
      if (line.includes(']')) {
        break;
      }
    } else {
      if (!restfulesStr) continue;
      restfulesStr += line;
      if (line.includes(']')) {
        endIndex = index;
        break;
      }
    }
  }
  if (!restfulesStr) {
    console.log('检测到router文件结构异常，请使用tf egg -r <filename> 命令重新生成');
    return;
  }
  let res = [];
  eval(`${restfulesStr};res = restfuls`);
  res.push(filename);
  res = [...new Set(res)];
  lines.splice(
    startIndex,
    endIndex > startIndex ? endIndex - startIndex + 1 : 1,
    `const restfuls = ${JSON.stringify(res)}`
  );
  await writeFileOnRoot(fileLocation, lines.join('\r\n'));
  log && spinner.succeed('处理完成');
};

/**
 * @description: 创建egg的相关文件, 对controller、service、model
 * @param {*} type
 * @param {*} filename
 * @return {*}
 */
const createEggOptionFile = async (type, filename, log = true) => {
  const savePath = `app/${type}`;
  const fileLocation = `${savePath}/${filename}.js`;

  if (existsSync(fileLocation, false)) {
    // 文件存在询问是否覆盖？
    const answers = await Inquirer.prompt([
      {
        type: 'input',
        name: 'res',
        message: `文件${fileLocation}已存在，是否覆盖？(y/n)`,
      },
    ]);
    if (answers.res === 'n') {
      return;
    }
  }
  const spinner = log ? Ora('正在载入...').start() : null;
  // 载入重命名
  await downloadGitTemp(`egg-${type}`, savePath);
  await renameFileOnRoot(`${savePath}/_egg_${type}.js`, fileLocation);
  const content = await readFileFromRoot(fileLocation);

  // 渲染模板
  const meta = {
    FirstUp: filename[0].toUpperCase() + filename.slice(1),
    name: filename,
  };
  const file = Handlebars.compile(content)(meta);
  await writeFileOnRoot(fileLocation, file);
  log && spinner.succeed('载入完成');
};

const eggCreateAll = async filename => {
  const spinner = Ora('正在载入...').start();
  await restfulRouter(filename, false);
  for (const type of ['controller', 'service', 'model']) {
    await createEggOptionFile(type, filename, false);
  }
  spinner.succeed('载入完成');
};

module.exports = {
  restfulRouter,
  createEggOptionFile,
  eggCreateAll,
};
